import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import type { IRootState } from './index'
import { Actions, Mutations } from '@/enum/tree'
import { getIndustryTag, getIndustry, getArea, getCQArea } from '@/api/tree'

export interface ITreeState {
  industryTag: unknown[]
  industry: unknown[]
  area: unknown[]
  city: unknown[]
  industryLevel0: unknown[]
  cqArea: unknown[]
}

export const state: () => ITreeState = () => ({
  industryTag: [],
  industry: [],
  area: [],
  city: [],
  industryLevel0: [],
  cqArea: [],
})

export const mutations: MutationTree<ITreeState> = {
  [Mutations.SET_INDUSTRY_TAG](state, payload) {
    state.industryTag = payload
  },
  [Mutations.SET_INDUSTRY](state, payload) {
    state.industry = payload
  },
  [Mutations.SET_AREA](state, payload) {
    state.area = payload
  },
  [Mutations.SET_CITY](state, payload) {
    state.city = payload
  },
  [Mutations.SET_INDUSTRY_LEVEL_0](state, payload) {
    state.industryLevel0 = payload
  },
  [Mutations.SET_CQ_AREA](state, payload) {
    state.cqArea = payload
  },
}

export const actions: ActionTree<ITreeState, IRootState> = {
  async [Actions.getIndustryTag]({ commit, state }) {
    if (state.industryTag.length === 0) {
      const result: any = await getIndustryTag()
      const tag = result.map((d: any) => ({
        label: d.name,
        value: d.id,
      }))
      commit(Mutations.SET_INDUSTRY_LEVEL_0, tag || [])
      commit(Mutations.SET_INDUSTRY_TAG, result || [])
    }
  },
  async [Actions.getIndustry]({ commit, state }) {
    if (state.industry.length === 0) {
      const result = await getIndustry()
      commit(Mutations.SET_INDUSTRY, result || [])
    }
  },
  async [Actions.getArea]({ commit, state }) {
    if (state.area.length === 0) {
      const result: any = await getArea()
      const city = result.map((d: any) => ({
        label: d.name,
        value: d.id,
      }))
      commit(Mutations.SET_CITY, city || [])
      commit(Mutations.SET_AREA, result || [])
    }
  },
  async [Actions.getCQArea]({ commit, state }) {
    if (state.cqArea.length === 0) {
      const result: any = await getCQArea()
      const area = result[0].children.map((d: any) => ({
        label: d.name,
        value: d.name, // 临时使用d.name   d.id,
      }))
      commit(Mutations.SET_CQ_AREA, area)
    }
  },
}

export const getters: GetterTree<ITreeState, IRootState> = {
  industryTag: (state) => state.industryTag,
  industry: (state) => state.industry,
  area: (state) => state.area,
  cqArea: (state) => state.cqArea,
  city: (state) => state.city,
  industryLevel0: (state) => state.industryLevel0,
}
